<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="状态" prop="status">
          <dict v-model="queryParams.status" code="clear_status" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button
          v-hasPerm="['stock:stockHolding:add']"
          type="success"
          @click="handleOpenDialog()"
        >
          <template #icon><Plus /></template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['stock:stockHolding:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon><Delete /></template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="code" label="股票代码" prop="code" min-width="80" align="center" />
        <el-table-column key="name" label="股票名称" prop="name" min-width="150" align="center" />
        <el-table-column key="income" label="收益额" prop="income" min-width="120" align="center" />
        <el-table-column key="yield" label="收益率" prop="yield" min-width="120" align="center" />
        <el-table-column
          key="startDate"
          label="建仓日期"
          prop="startDate"
          min-width="100"
          align="center"
        />
        <el-table-column
          key="endDate"
          label="清仓日期"
          prop="endDate"
          min-width="100"
          align="center"
        />

        <el-table-column label="状态" width="150" align="center">
          <template #default="scope">
            <DictLabel v-model="scope.row.status" code="clear_status" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['stock:stockHolding:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon><Edit /></template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['stock:stockTrading:query']"
              type="primary"
              size="small"
              link
              @click="handleOpenTradingTableDialog(scope.row)"
            >
              <template #icon><Tickets /></template>
              交易
            </el-button>
            <el-button
              v-hasPerm="['stock:stockHolding:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon><Delete /></template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 持仓管理表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-input v-model="formData.id" type="hidden" />
        <el-form-item label="股票代码" prop="code">
          <el-input v-model="formData.code" placeholder="股票代码" />
        </el-form-item>

        <el-form-item label="股票名称" prop="name">
          <el-input v-model="formData.name" placeholder="股票名称" />
        </el-form-item>

        <el-form-item label="收益额" prop="income">
          <el-input v-model="formData.income" placeholder="收益额" />
        </el-form-item>

        <el-form-item label="收益率" prop="yield">
          <el-input v-model="formData.yield" placeholder="收益率" />
        </el-form-item>

        <el-form-item label="建仓日期" prop="startDate">
          <el-date-picker
            v-model="formData.startDate"
            class="!w-[240px]"
            type="date"
            placeholder="建仓日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="清仓日期" prop="endDate">
          <el-date-picker
            v-model="formData.endDate"
            class="!w-[240px]"
            type="date"
            placeholder="清仓日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <dict v-model="formData.status" class="!w-[240px]" code="clear_status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 交易列表弹窗 -->
    <el-dialog
      v-model="tradingTableDialog.visible"
      :title="tradingTableDialog.title"
      width="1200px"
      @close="handleCloseTradingTableDialog"
    >
      <div class="search-bar">
        <el-form ref="tradingQueryFormRef" :model="tradingQueryParams" :inline="true">
          <el-form-item>
            <el-button type="primary" @click="handleTradingQuery">
              <template #icon><Search /></template>
              搜索
            </el-button>
            <el-button @click="handleResetTradingQuery">
              <template #icon><Refresh /></template>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-card shadow="never">
        <div class="mb-10px">
          <el-button
            v-hasPerm="['stock:stockTrading:add']"
            type="success"
            @click="handleOpenTradingEditDialog()"
          >
            <template #icon><Plus /></template>
            新增
          </el-button>
          <el-button
            v-hasPerm="['stock:stockTrading:delete']"
            type="danger"
            :disabled="tradingRemoveIds.length === 0"
            @click="handleTradingDelete()"
          >
            <template #icon><Delete /></template>
            删除
          </el-button>
        </div>
        <el-table
          ref="tradingDataTableRef"
          v-loading="tradingLoading"
          :data="tradingPageData"
          highlight-current-row
          border
          @selection-change="handleTradingSelectionChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column key="date" label="交易日期" prop="date" min-width="100" align="center" />
          <el-table-column key="price" label="价格" prop="price" min-width="80" align="center" />
          <el-table-column key="number" label="数量" prop="number" min-width="80" align="center" />
          <el-table-column key="amount" label="总金额" prop="price" min-width="80" align="center" />
          <el-table-column
            key="commission"
            label="佣金"
            prop="price"
            min-width="80"
            align="center"
          />
          <el-table-column
            key="stampTax"
            label="印花税"
            prop="price"
            min-width="80"
            align="center"
          />
          <el-table-column key="fee" label="总费用" prop="price" min-width="80" align="center" />
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <DictLabel v-model="scope.row.status" code="tran_verify_status" />
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="220">
            <template #default="scope">
              <el-button
                v-hasPerm="['stock:stockTrading:edit']"
                type="primary"
                size="small"
                link
                @click="handleOpenTradingEditDialog(scope.row.id)"
              >
                <template #icon><Edit /></template>
                编辑
              </el-button>
              <el-button
                v-hasPerm="['stock:stockTrading:delete']"
                type="danger"
                size="small"
                link
                @click="handleTradingDelete(scope.row.id)"
              >
                <template #icon><Delete /></template>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-if="total > 0"
          v-model:total="tradingTotal"
          v-model:page="tradingQueryParams.pageNum"
          v-model:limit="tradingQueryParams.pageSize"
          @pagination="handleTradingQuery()"
        />
      </el-card>
    </el-dialog>

    <!-- 交易管理表单弹窗 -->
    <el-dialog
      v-model="tradingEditDialog.visible"
      :title="tradingEditDialog.title"
      width="500px"
      @close="handleCloseTradingEditDialog"
    >
      <el-form
        ref="tradingDataFormRef"
        :model="tradingFormData"
        :rules="tradingRules"
        label-width="100px"
      >
        <el-input v-model="tradingFormData.id" type="hidden" />
        <el-input v-model="tradingFormData.holdingId" type="hidden" />
        <el-form-item label="交易日期" prop="date">
          <el-date-picker
            v-model="tradingFormData.date"
            class="!w-[240px]"
            type="date"
            placeholder="交易日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="tradingFormData.price"
            class="!w-[240px]"
            :precision="2"
            placeholder="价格"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="数量" prop="number">
          <el-input-number
            v-model="tradingFormData.number"
            class="!w-[240px]"
            :precision="0"
            :step="100"
            placeholder="数量"
          >
            <template #suffix>
              <span>股</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="总金额" prop="amount">
          <el-input-number
            v-model="tradingFormData.amount"
            class="!w-[240px]"
            :precision="2"
            placeholder="总金额"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="佣金" prop="commission">
          <el-input-number
            v-model="tradingFormData.commission"
            class="!w-[240px]"
            :precision="2"
            placeholder="佣金"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="印花税" prop="stampTax">
          <el-input-number
            v-model="tradingFormData.stampTax"
            class="!w-[240px]"
            :precision="2"
            placeholder="印花税"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="总费用" prop="fee">
          <el-input-number
            v-model="tradingFormData.fee"
            class="!w-[240px]"
            :precision="2"
            placeholder="总费用"
          >
            <template #suffix>
              <span>元</span>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <dict v-model="tradingFormData.status" class="!w-[240px]" code="tran_verify_status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleTradingSubmit()">确定</el-button>
          <el-button @click="handleCloseTradingEditDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "StockHolding",
  inheritAttrs: false,
});

import StockHoldingAPI, {
  StockHoldingPageVO,
  StockHoldingForm,
  StockHoldingPageQuery,
} from "@/api/stock/stock-holding";

import StockTradingAPI, {
  StockTradingPageVO,
  StockTradingForm,
  StockTradingPageQuery,
} from "@/api/stock/stock-trading";

const queryFormRef = ref(ElForm);
const tradingQueryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);
const tradingDataFormRef = ref(ElForm);

const loading = ref(false);
const tradingLoading = ref(false);
const removeIds = ref<number[]>([]);
const tradingRemoveIds = ref<number[]>([]);
const total = ref(0);
const tradingTotal = ref(0);

const queryParams = reactive<StockHoldingPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const tradingQueryParams = reactive<StockTradingPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 持仓管理表格数据
const pageData = ref<StockHoldingPageVO[]>([]);

// 交易管理表格数据
const tradingPageData = ref<StockTradingPageVO[]>([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 交易列表弹窗
const tradingTableDialog = reactive({
  title: "",
  visible: false,
});

// 交易编辑弹窗
const tradingEditDialog = reactive({
  title: "",
  visible: false,
});

// 持仓管理表单数据
const formData = reactive<StockHoldingForm>({});

// 交易管理表单数据
const tradingFormData = reactive<StockTradingForm>({});

// 选择交易后临时持仓ID
const storeHoldingId = ref(0);

// 持仓管理表单校验规则
const rules = reactive({
  code: [{ required: true, message: "请输入股票代码", trigger: "blur" }],
  name: [{ required: true, message: "请输入股票名称", trigger: "blur" }],
});

// 交易管理表单校验规则
const tradingRules = reactive({
  date: [{ required: true, message: "请输入交易日期", trigger: "blur" }],
  price: [{ required: true, message: "请输入价格", trigger: "blur" }],
  number: [{ required: true, message: "请输入数量", trigger: "blur" }],
  amount: [{ required: true, message: "请输入总金额", trigger: "blur" }],
  commission: [{ required: true, message: "请输入佣金", trigger: "blur" }],
  stampTax: [{ required: true, message: "请输入印花税", trigger: "blur" }],
  fee: [{ required: true, message: "请输入总手续费", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

/** 查询持仓管理 */
function handleQuery() {
  loading.value = true;
  StockHoldingAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 查询交易管理 */
function handleTradingQuery() {
  tradingLoading.value = true;
  StockTradingAPI.getPage(tradingQueryParams)
    .then((data) => {
      tradingPageData.value = data.list;
      tradingTotal.value = data.total;
    })
    .finally(() => {
      tradingLoading.value = false;
    });
}

/** 重置持仓管理查询 */
function handleResetQuery() {
  queryFormRef.value!.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 重置交易管理查询 */
function handleResetTradingQuery() {
  tradingQueryFormRef.value!.resetFields();
  tradingQueryParams.pageNum = 1;
  tradingQueryParams.holdingId = storeHoldingId.value;
  handleTradingQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection: any) {
  removeIds.value = selection.map((item: any) => item.id);
}

/** 交易表格行复选框选中记录选中ID集合 */
function handleTradingSelectionChange(selection: any) {
  tradingRemoveIds.value = selection.map((item: any) => item.id);
}

/** 打开持仓管理弹窗 */
function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改持仓管理";
    StockHoldingAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增持仓管理";
  }
}

/** 打开交易列表弹窗 */
function handleOpenTradingTableDialog(row: Record<string, any>) {
  console.log(row);
  tradingTableDialog.visible = true;
  tradingTableDialog.title = row.code + " - " + row.name;
  storeHoldingId.value = row.id;
  tradingQueryParams.holdingId = row.id;
  StockTradingAPI.getPage(tradingQueryParams)
    .then((data) => {
      tradingPageData.value = data.list;
      tradingTotal.value = data.total;
    })
    .finally(() => {
      tradingLoading.value = false;
    });
}

/** 打开交易管理弹窗 */
function handleOpenTradingEditDialog(id?: number) {
  tradingEditDialog.visible = true;
  tradingFormData.holdingId = storeHoldingId.value;
  if (id) {
    tradingEditDialog.title = "修改交易管理";
    StockTradingAPI.getFormData(id).then((data) => {
      Object.assign(tradingFormData, data);
    });
  } else {
    tradingEditDialog.title = "新增交易管理";
    tradingFormData.commission = 0.0;
    tradingFormData.stampTax = 0.0;
    tradingFormData.fee = 0.0;
    tradingFormData.status = "N";
  }
}

/** 提交持仓管理表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        StockHoldingAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        StockHoldingAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 提交交易管理表单 */
function handleTradingSubmit() {
  tradingDataFormRef.value.validate((valid: any) => {
    if (valid) {
      tradingLoading.value = true;
      const id = tradingFormData.id;
      if (id) {
        StockTradingAPI.update(id, tradingFormData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseTradingEditDialog();
            handleResetTradingQuery();
          })
          .finally(() => (tradingLoading.value = false));
      } else {
        StockTradingAPI.add(tradingFormData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseTradingEditDialog();
            handleResetTradingQuery();
          })
          .finally(() => (tradingLoading.value = false));
      }
    }
  });
}

/** 关闭持仓管理弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  formData.id = undefined;
}

/** 关闭交易列表弹窗 */
function handleCloseTradingTableDialog() {
  tradingTableDialog.visible = false;
  tradingQueryFormRef.value.resetFields();
  tradingQueryFormRef.value.clearValidate();
  storeHoldingId.value = 0;
}

/** 关闭交易管理弹窗 */
function handleCloseTradingEditDialog() {
  tradingEditDialog.visible = false;
  tradingDataFormRef.value.resetFields();
  tradingDataFormRef.value.clearValidate();
  tradingQueryParams.holdingId = storeHoldingId.value;
  tradingFormData.id = undefined;
}

/** 删除持仓管理 */
function handleDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      StockHoldingAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

/** 删除交易管理 */
function handleTradingDelete(id?: number) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      tradingLoading.value = true;
      StockTradingAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetTradingQuery();
        })
        .finally(() => (tradingLoading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
